var querystring=require("querystring");
var formidable=require("formidable");
var fs=require("fs");
//index
function index(response,request){
    console.log("请求处理index地址");

    var html="";
    html+="<!DOCTYPE html>";
    html+="<html>";
    html+="<head>";
    html+="<meta charset='utf-8' />";
    html+="<title></title>";
    html+="</head>";
    html+="<body>";
    html+="<form action='/validatelogin' method='post'>";
    html+="username:<input type='text' name='username'/><br />";
    html+="password:<input type='text' name='password'/><br />";
    html+="<input type='submit' value='提交'/>";
    html+="</form>";
    html+="</body>";
    html+="</html>";


    response.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    response.write(html);      
    response.end(); 
}

//start
function start(response,request) {
    // body...
    console.log("请求处理start地址");

    var html="";
    html+="<!DOCTYPE html>";
    html+="<html>";
    html+="<head>";
    html+="<meta charset='utf-8' />";
    html+="<title></title>";
    html+="</head>";
    html+="<body>";
    html+='<form action="/upload" method="post" enctype="multipart/form-data">';
    html+='提交的文件名称：<input type="text" name="title" /><br/>';
    html+='上传的文件：<input type="file" name="upload" id="upload" multiple="multiple" /><br/>';
    html+="<input type='submit' value='提交'/>";
    html+="</form>";
    html+="</body>";
    html+="</html>";

    response.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
    response.write(html);      
    response.end(); 
}

//upload
function upload(response, request) {
    console.log("请求处理upload上传");
    var form = new formidable.IncomingForm();
    
    // 设置文件上传临时目录
    form.uploadDir = "./tmp";
    // 保持文件扩展名
    form.keepExtensions = true;

    form.parse(request, function(error, fields, files) {
        if (error) {
            console.error("解析文件出错：", error);
            response.writeHead(500, {"Content-Type": "text/plain;charset=utf-8"});
            response.write("文件上传失败");
            response.end();
            return;
        }

        console.log("parsing done");
        // console.log("files:", files);

        // 确保上传的文件存在
        if (!files || !files.upload || !files.upload[0]) {
            response.writeHead(400, {"Content-Type": "text/plain;charset=utf-8"});
            response.write("没有找到上传的文件");
            response.end();
            return;
        }

        try {
            // 使用新版本的文件对象结构获取文件路径
            const uploadedFile = files.upload[0];
            const oldPath = uploadedFile.filepath;
            const newPath = "./tmp/test.png";
            
            fs.renameSync(oldPath, newPath);
            
            response.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
            response.write("接收到图片<br/>");
            response.write("<img src='/show'/>");
            response.end();
        } catch (err) {
            console.error("移动文件时出错：", err);
            response.writeHead(500, {"Content-Type": "text/plain;charset=utf-8"});
            response.write("保存文件时发生错误");
            response.end();
        }
    });
}

//validatelogin
function validatelogin(response,request){
    var postData="";

    request.setEncoding("utf8");

    request.addListener("data",function(postDataChunk) {
        // body...
    postData+=postDataChunk;
    console.log("接收的Post数据"+postDataChunk);

    });    
    
    request.addListener("end",function(){
           //调用router模块里的route方法
        console.log("请求处理validatelogin地址");
        var username=querystring.parse(postData).username;
        var password=querystring.parse(postData).password;

        if(username=="admin"&&password=="123456"){
           // 密码验证成功
           response.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"});
           response.write("密码验证成功");   
           response.end();
        }else{
           //密码验证不成功
           response.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"});
           response.write("密码验证不成功");   
           response.end();
        }
    });   
}

function show(response) {
    fs.readFile("./tmp/test.png", "binary", function(error, file) {
        if (error) {
            console.error("读取图片错误:", error);
            response.writeHead(500, {"Content-Type": "text/plain;charset=utf-8"});
            response.write("无法读取图片：" + error.message);   
            response.end();
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");   
            response.end();
        }
    });
}

exports.start=start;
exports.upload=upload;
exports.index=index;
exports.validatelogin=validatelogin;
exports.show=show;